//
//  ADJgSDKBannerAdapter.m
//  AnyThinkSDKDemo
//
//  Created by 刘娟 on 2024/9/24.
//  Copyright © 2024 抽筋的灯. All rights reserved.
//

#import "ADJgSDKBannerAdapter.h"
#import <ADJgSDK/ADJgSDK.h>
#import "ADJgSDKBannerCustomEvent.h"
#import "ATADJgSDKBiddingManager.h"
#import "ATADJgSDKBiddingRequest.h"
#import "ADJgSDKBannerAdContainer.h"
@interface ADJgSDKBannerAdapter()
@property(nonatomic, readonly) ADJgSDKBannerCustomEvent *customEvent;
@property(nonatomic, strong)ADJgSDKBannerAdContainer *bannerAdContainer;
@end

@implementation ADJgSDKBannerAdapter
- (instancetype)initWithNetworkCustomInfo:(NSDictionary *)serverInfo localInfo:(NSDictionary *)localInfo {
    self = [super init];
    if (self != nil) {
        if (![[ATAPI sharedInstance] initFlagForNetwork:@"ADJgSDK"]) {
            [[ATAPI sharedInstance] setInitFlagForNetwork:@"ADJgSDK"];
            [ADJgSDK initWithAppId:serverInfo[@"app_id"] completionBlock:^(NSError * _Nullable error) {
                if(error){
                    [[ATAPI sharedInstance] setInitFlag:0 forNetwork:@"ADJgSDK"];
                    NSLog(@"ADJgSDK init failed：%@",error);
                }
            }];
                    
        }
        
    }
    return self;
}


- (void)loadADWithInfo:(NSDictionary *)serverInfo localInfo:(NSDictionary *)localInfo completion:(void (^)(NSArray *, NSError *))completion {

    NSDictionary *extraInfo = localInfo;
    CGSize adSize = [extraInfo[kATAdLoadingExtraBannerAdSizeKey] respondsToSelector:@selector(CGSizeValue)] ? [extraInfo[kATAdLoadingExtraBannerAdSizeKey] CGSizeValue] : CGSizeMake(320.0f, 50.0f);

    _customEvent = [[ADJgSDKBannerCustomEvent alloc] initWithInfo:serverInfo localInfo:localInfo];
    _customEvent.requestCompletionBlock = completion;
        NSString *bidId = serverInfo[kATAdapterCustomInfoBuyeruIdKey];
        if (bidId.length) {
            
            ATADJgSDKBiddingRequest *request = [[ATADJgSDKBiddingManager sharedInstance] getRequestItemWithUnitID:serverInfo[@"slot_id"]];
            
            if (request.customObject!=nil) { // load secced
                self.bannerAdContainer = request.customObject;
                self.bannerAdContainer.delegate = self->_customEvent;
                self->_customEvent.bannerAdContainer = self.bannerAdContainer;
                [self->_customEvent trackBannerAdLoaded:self.bannerAdContainer.bannerView adExtra:nil];
            } else { // fail
                NSError *error = [NSError errorWithDomain:ATADLoadingErrorDomain code:-1000001 userInfo:@{NSLocalizedDescriptionKey:@"AT has failed to load intertitial.", NSLocalizedFailureReasonErrorKey:@"It took too long to load placement stragety."}];
                [self->_customEvent trackBannerAdLoadFailed:nil];
            }
            [[ATADJgSDKBiddingManager sharedInstance] removeRequestItmeWithUnitID:serverInfo[@"slot_id"]];
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self->_customEvent loadBannerWithPosId:serverInfo[@"slot_id"] frame:CGRectMake(.0f, .0f, adSize.width, adSize.height)];
            });
        }
    
}

#pragma mark - Header bidding
#pragma mark - c2s
+ (void)bidRequestWithPlacementModel:(ATPlacementModel*)placementModel unitGroupModel:(ATUnitGroupModel*)unitGroupModel info:(NSDictionary*)info completion:(void(^)(ATBidInfo *bidInfo, NSError *error))completion {

    NSLog(@"%s", __FUNCTION__);
    if (NSClassFromString(@"ADJgSDK") == nil) {
        if (completion != nil) { completion( nil, [NSError errorWithDomain:@"com.ubix.mediation.ios" code:1 userInfo:@{NSLocalizedDescriptionKey:@"Bid request has failed", NSLocalizedFailureReasonErrorKey:@"ADJgSDK is not imported"}]); }
        return;
    }
    
    if (![[ATAPI sharedInstance] initFlagForNetwork:@"ADJgSDK"]) {
        [[ATAPI sharedInstance] setInitFlagForNetwork:@"ADJgSDK"];
        [ADJgSDK initWithAppId:info[@"app_id"] completionBlock:^(NSError * _Nullable error) {
            if (error){
                [[ATAPI sharedInstance] setInitFlag:0 forNetwork:@"ADJgSDK"];
                NSLog(@"ADJgSDK - 初始化失败%@",error);
            } else {
                NSDictionary *extraInfo = info;
                CGSize adSize = [extraInfo[kATAdLoadingExtraBannerAdSizeKey] respondsToSelector:@selector(CGSizeValue)] ? [extraInfo[kATAdLoadingExtraBannerAdSizeKey] CGSizeValue] : CGSizeMake(320.0f, 50.0f);
                dispatch_async(dispatch_get_main_queue(), ^{
                ATADJgSDKBiddingManager *biddingManage = [ATADJgSDKBiddingManager sharedInstance];
                ATADJgSDKBiddingRequest *request = [ATADJgSDKBiddingRequest new];
                request.unitGroup = unitGroupModel;
                request.placementID = placementModel.placementID;
                request.bidCompletion = completion;
                request.unitID = info[@"slot_id"];
                request.extraInfo = info;
                request.adType = ESCAdFormatBanner;
                ADJgSDKBannerAdContainer *bannerAdContainer = [[ADJgSDKBannerAdContainer alloc] initPosId:info[@"slot_id"] delegate:nil frame:CGRectMake(0, 0, adSize.width, adSize.height)];
                    UIViewController *viewController = [ATBannerCustomEvent rootViewControllerWithPlacementID:((ATPlacementModel*)info[kATAdapterCustomInfoPlacementModelKey]).placementID requestID:info[kATAdapterCustomInfoRequestIDKey]];
                    bannerAdContainer.controller = viewController;
                request.customObject = bannerAdContainer;
                [biddingManage startWithRequestItem:request];
                });
            }
        }];
                
    }else{
        NSDictionary *extraInfo = info;
        CGSize adSize = [extraInfo[kATAdLoadingExtraBannerAdSizeKey] respondsToSelector:@selector(CGSizeValue)] ? [extraInfo[kATAdLoadingExtraBannerAdSizeKey] CGSizeValue] : CGSizeMake(320.0f, 50.0f);
        dispatch_async(dispatch_get_main_queue(), ^{
        ATADJgSDKBiddingManager *biddingManage = [ATADJgSDKBiddingManager sharedInstance];
        ATADJgSDKBiddingRequest *request = [ATADJgSDKBiddingRequest new];
        request.unitGroup = unitGroupModel;
        request.placementID = placementModel.placementID;
        request.bidCompletion = completion;
        request.unitID = info[@"slot_id"];
        request.extraInfo = info;
        request.adType = ESCAdFormatBanner;
        ADJgSDKBannerAdContainer *bannerAdContainer = [[ADJgSDKBannerAdContainer alloc] initPosId:info[@"slot_id"] delegate:nil frame:CGRectMake(0, 0, adSize.width, adSize.height)];
            UIViewController *viewController = [ATBannerCustomEvent rootViewControllerWithPlacementID:((ATPlacementModel*)info[kATAdapterCustomInfoPlacementModelKey]).placementID requestID:info[kATAdapterCustomInfoRequestIDKey]];
            bannerAdContainer.controller = viewController;
        request.customObject = bannerAdContainer;
        [biddingManage startWithRequestItem:request];
        });
    }
        
}
+ (BOOL)adReadyWithCustomObject:(id)customObject info:(NSDictionary *)info {
    return customObject;
}

@end
